package com.wu.store.config.resolver;

import com.alibaba.fastjson.JSON;
import com.wu.store.annotation.CurrentUser;
import com.wu.store.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.Serializable;

public class CurrentUserArgumentsResolver implements HandlerMethodArgumentResolver {

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Override
	public boolean supportsParameter(MethodParameter methodParameter) {
		return methodParameter.hasParameterAnnotation(CurrentUser.class);
	}

	@Override
	public User resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String sessionId = (String) session.getId();
		User user = null;
		ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
		String userStr = stringStringValueOperations.get(sessionId);
		if (StringUtils.isNotEmpty(userStr)) {
			user = JSON.parseObject(userStr, User.class);
		}
		if (user == null) {
			throw new Exception("请登录");
		}
		return user;
	}
}
